﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using SuperInterMarket.Data;
using System.IO;

namespace SuperInterMarket.Mail
{
    public partial class ToAddressManage : Form
    {
        public ToAddressManage()
        {
            InitializeComponent();
        }

        private List<XElement> GetXElements()
        {
            XDocument doc = XDocument.Load(SysConstants.ToAddressFile);
            XElement config = doc.Element("config");
            List<XElement> toadds = config.Elements("toadd").ToList<XElement>();
            return toadds;
        }


        private List<ToAddress> GetToAddresses(List<XElement> xes)
        {
            List<ToAddress> allTos = new List<ToAddress>();

            if (xes.Count > 0)
            {
                foreach (var item in xes)
                {
                    ToAddress toAddress = new ToAddress();
                    toAddress.Type = item.Attribute("type").Value;
                    toAddress.Email = item.Attribute("email").Value;
                    allTos.Add(toAddress);
                }
            }
            return allTos;
        }

        private void ToAddressManage_Load(object sender, EventArgs e)
        {
            LoadDataGridView();
        }

        public void LoadDataGridView()
        {
            ToAddressDataGridView.DataSource = GetToAddresses(GetXElements());
            Numlabel.Text = GetToAddresses(GetXElements()).Count.ToString();
        }

        private void AddToAddBt_Click(object sender, EventArgs e)
        {
            AddToAddress addTo = new AddToAddress(this);
            addTo.ShowDialog();
        }

        private void DeleteTypeBt_Click(object sender, EventArgs e)
        {
            if (ToAddressDataGridView.SelectedRows.Count == 0)
            {
                MessageBox.Show("至少选择一个");
                return;
            }

            string email = (string)((ToAddressDataGridView.SelectedRows)[0]).Cells[0].Value;
            string type = (string)((ToAddressDataGridView.SelectedRows)[0]).Cells[1].Value;

            XDocument doc = XDocument.Load(SysConstants.ToAddressFile);
            XElement config = doc.Element("config");
            List<XElement> toadds = config.Elements("toadd").ToList<XElement>();
            if (toadds.Count > 0)
            {
                XElement element = toadds.Where(c => c.Attribute("type").Value == type).Where(c => c.Attribute("email").Value == email).SingleOrDefault();
                if (element != null)
                {
                    element.Remove();
                }
            }
            doc.Save(SysConstants.ToAddressFile);
            LoadDataGridView();
        }

        private void SelectTypeBt_Click(object sender, EventArgs e)
        {
            string email = EmailTxt.Text;
            string type = TypeComboBox.Text;
            XDocument doc = XDocument.Load(SysConstants.ToAddressFile);
            XElement config = doc.Element("config");
            List<XElement> toadds = config.Elements("toadd").ToList<XElement>();
            if (toadds.Count > 0)
            {
                if (!string.IsNullOrEmpty(email))
                {
                    toadds = toadds.Where(c => c.Attribute("email").Value == email).ToList();
                }
                if (!string.IsNullOrEmpty(type))
                {
                    toadds = toadds.Where(c => c.Attribute("type").Value == type).ToList();
                }
            }
            ToAddressDataGridView.DataSource = GetToAddresses(toadds);
            Numlabel.Text = toadds.Count.ToString();
        }
        string fileName = "";
        string fileType = "";
        string fileSize = "";
        byte[] file;
        private void ImportMailBt_Click(object sender, EventArgs e)
        {
            string strfile = "";
            OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
            OpenFileDialog1.Filter = "Text files (*.txt)|*.txt";
            OpenFileDialog1.FilterIndex = 0;
            OpenFileDialog1.Title = "";
            OpenFileDialog1.Multiselect = false;
            if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (OpenFileDialog1.FileName.Length != 0)
                {
                    strfile = OpenFileDialog1.FileName;//获取文件路径
                    OpenFileDialog1.AddExtension = true;
                    fileName = Path.GetFileName(strfile);//获取文件名
                    fileType = fileName.Substring(fileName.IndexOf(".") + 1);
                    string line;
                    StreamReader file = new StreamReader(strfile);


                    List<ToAddress> toAdds = new List<ToAddress>();
                    while ((line = file.ReadLine()) != null)
                    {
                        if (line.IndexOfAny(new char[]{',', ';'})!=-1)
                        {
                            line = line.Substring(0,line.Length-1);
                        }
                        ToAddress temp = new ToAddress();
                        if (UtilTool.IsEmail(line))
                        {
                            temp.Email = line;
                            int pos = line.IndexOf("@");
                            string LastResult = line.Substring(pos+1, line.Length - pos-1);
                            int pointPos = LastResult.IndexOf(".");
                            temp.Type = LastResult.Substring(0, pointPos);
                            toAdds.Add(temp);
                        }
                        else
                        {
                            if (UtilTool.IsNumber(line))
                            {
                                temp.Email = line + "@qq.com";
                                temp.Type = "qq";
                                toAdds.Add(temp);
                            }
                        }
                        
                        
                    }
                    AddToFile(toAdds);
                    file.Close();
                    MessageBox.Show("导入成功");
                    LoadDataGridView();
                }
                else
                {
                    MessageBox.Show("请重新选择！");
                    return;
                }
            }
        }


        private void AddToFile(List<ToAddress> newToadds)
        {
            XDocument doc = XDocument.Load(SysConstants.ToAddressFile);
            XElement config = doc.Element("config");
            List<XElement> toadds = config.Elements("toadd").ToList<XElement>();

            if (newToadds.Count>0)
            {
                foreach (var item in newToadds)
                {
                    XElement temp = toadds.Where(c => c.Attribute("email").Value == item.Email).SingleOrDefault();
                    if (temp!=null)
                    {
                        continue;
                    }
                    XElement newXelement = new XElement("toadd");
                    newXelement.Add(new XAttribute("email",item.Email));
                    newXelement.Add(new XAttribute("type",item.Type));
                    config.AddFirst(newXelement);
                    toadds.Add(newXelement);
                }
                
            }

            doc.Save(SysConstants.ToAddressFile);

        }
       
    }
}
